Trò chơi toán học bằng Python
1 import sqlite3
2 import random
3 db = sqlite3.connect('database.db')
4 c=db.cursor()
5 c.execute("CREATE TABLE IF NOT EXISTS data(name TEXT , highscore REAL)")
6 db.commit()
7
8 def welcome(name,highscore): # Display the welcoming message
9 print(" Hello {} ! \n\n Welcome to Maths game \n\n Your high score : {}\n\n____________________________________________________________\n\n".format(name,highscore))
10 input("Press Enter to start")
11
12 def main():
13 print("____________________________________________________________\n\n [MATH GAME]\n\n____________________________________________________________\n")
14 data=c.execute("SELECT * FROM data")
15
16 # Count the number of the table's rows
17 x=0
18 for i in data:
19 x=x+1
20
21 if x==0: # If empty (first run)
22 # Ask about the user name
23 ask=True
24 while ask:
25 try:
26 name = input("[+] Please Enter your name : ")
27 if name=="" or len(name)==0:
28 print("Please Enter a valid value !")
29 else:
30 ask=False
31 except valueError:
32 print("Please Enter a valid value")
33 askName()
34
35 print("\n___________________________________________________________\n")
36 c.execute("INSERT INTO data VALUES(?,?)",(name,"0")) # Set the name in database
37 db.commit()
38 welcome(name,"0")
39 highscore=0
40
41 else: # User played before
42 data=c.execute("SELECT * FROM data")
43 for i in data: # Get the name and highscore
44 name=i[0]
45 highscore=i[1]
46 welcome(name,highscore)
47
48 score=0
49 lose=False
50 while lose!=True:
51 calc=random.randint(0,1) # Generate a random calculation type 0=[+] 1=[*]
52
53 if calc==0: #(+)
54 fnum=random.randint(2,50) # First number
55 snum=random.randint(2,50) # Second number
56 result=fnum+snum
57 inp="[+] {} + {} = " # User input text
58
59 else: #(*)
60 fnum=random.randint(1,10)
61 snum=random.randint(1,10)
62 result=fnum * snum
63 inp="[+] {} * {} ="
64
65 def askUser(): # Ask user what is the result
66 userInput=input(inp.format(fnum,snum))
67 try:
68 userInput=int(userInput) # Try to make input as int
69 return userInput
70 except: # If user input a text or leaft it empty
71 print("Enter a valid value")
72 askUser() # Reask again
73 userInput=askUser()
74
75 if userInput==result: # Correct answer
76 score=score+1
77 if score>highscore: # If this score is the high score
78 c.execute("UPDATE data SET highscore = ? WHERE name = ?",(score,name)) # Change highscore in database
79 db.commit()
80 print("Correct ! , High score ! your score : {} ".format(score)) # Show message
81 else: # The score is not the highscore
82 print("Correct ! your score : {}".format(score))
83
84 else: # Wrong answer
85 score=0
86 print("Oops ! Wrong Answer!")
87 userAgain=input("[+] Play again? (y,n) : ").lower()
88 if userAgain=="n":
89 print("Good bye !")
90 db.close()
91 lose=True
92 main()